import * as THREE from '../../build/three.module.js';
import {
  OrbitControls
} from '../../jsm/controls/OrbitControls.js';
import DAT from '../../jsm/libs/dat.gui.module.js';

const dat = new DAT.GUI();

const scene = new THREE.Scene();

const boxGeo = new THREE.BoxGeometry(10, 50, 10);
const boxMat = new THREE.MeshPhongMaterial({
  color: 0xff0000,
  side: THREE.DoubleSide
});
const boxMesh = new THREE.Mesh(boxGeo, boxMat);
boxMesh.name = 'box';
const group = new THREE.Group();
group.add(boxMesh);
scene.add(group);

/**
 * 构建动画
 */
const duration = 30;
const posKFT = new THREE.KeyframeTrack('box.position', [0, duration], [0, 0, 0, 0, 300, 0]);
const clip = new THREE.AnimationClip('position', duration, [posKFT]);
const mixer = new THREE.AnimationMixer(group);
const action = mixer.clipAction(clip);
action.timeScale = 1;
action.play();


const al = new THREE.AmbientLight(0xffffff);
scene.add(al);

const axesH = new THREE.AxesHelper(300);
scene.add(axesH);

const k = innerWidth / innerHeight,
      s = 60,
      camera = new THREE.PerspectiveCamera(s, k, 1, 10000);
camera.position.set(400, 400, 400);
camera.lookAt(scene.position);

const renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0x000000);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

new OrbitControls(camera, renderer.domElement);

const clock = new THREE.Clock();

(function render() {
  renderer.render(scene, camera);
  requestAnimationFrame(render);

  mixer.update(clock.getDelta());
})();

/**
 * 构建 dat.GUI 控制器
 */
const actionOpr = {
  time: 0,
  duration: 0,
  特定时间段: function () {
    if (this.duration < this.time) {
      console.error('数值错误，duration 不能小于 time');
      return;
    }
    action.time = this.time;
    clip.duration = this.duration;
    action.play();
  },
  某个时间点: function () {
    action.loop = THREE.LoopOnce;
    action.clampWhenFinished = true;
    action.time = this.time;
    clip.duration = action.time;
    action.play();
  }
}

const actionFloader = dat.addFolder('操作对象');
actionFloader.add(action, 'timeScale');
actionFloader.add(action, 'paused');

const oprFloader = dat.addFolder('效果');
oprFloader.add(actionOpr, 'time', 0, duration, 1);
oprFloader.add(actionOpr, 'duration', 0, duration, 1);
oprFloader.add(actionOpr, '特定时间段');
oprFloader.add(actionOpr, '某个时间点');